package com.ma.netana.controller;

import com.alibaba.fastjson.JSON;
import com.ma.netana.dao.PacketDao;
import jpcap.packet.ARPPacket;
import jpcap.packet.ICMPPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.UDPPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

@Controller
@RequestMapping("/packet")
public class PacketController {
    @Autowired
    PacketDao packetDao;

    jpcap.packet.IPPacket ipPacket;

    public void setPacket(IPPacket ipPacket) {
        this.ipPacket = ipPacket;
    }

    @RequestMapping("/getIPPacket")
    @CrossOrigin
    public String getPacket(Model model){
        System.out.println("======getPacket======");

        jpcap.packet.IPPacket ipPacket_1 = (jpcap.packet.IPPacket) packetDao.getIPPacket();

        JSON json =(JSON) JSON.toJSON(ipPacket_1);
        model.addAttribute("IPPacket",ipPacket_1);
        this.ipPacket = ipPacket_1;
        return "dashboard";
    }

    @RequestMapping("/getARPPacket")
    @CrossOrigin
    public String getARPPacket(Model model){
        System.out.println("======getARPPacket======");

        ARPPacket arpPacket =(ARPPacket) packetDao.getARPPAcket();



        JSON json =(JSON) JSON.toJSON(arpPacket);
        model.addAttribute("ARPPacket",arpPacket);
        model.addAttribute("ARPPacket",arpPacket);
        return "ARP";
    }

    @RequestMapping("/getUDPPacket")
    @CrossOrigin
    public String getICMPPacket(Model model){
        System.out.println("======getUDPPacket======");

        UDPPacket udpPacket =(UDPPacket) packetDao.getUDPPAcket();

        JSON json =(JSON) JSON.toJSON(udpPacket);
        model.addAttribute("UDPPacket",udpPacket);
        return "UDP";
    }

    @RequestMapping("/savePacket")
    @CrossOrigin
    public String savePacket() throws UnknownHostException {
        System.out.println("=========savePacket========");
        System.out.println("IPpacket:"+" "+ipPacket);

        packetDao.savePacket(ipPacket);
        return "redirect:/main.html";
    }
}
